const app = getApp();

import mapdata from '../../utils/xinjiang_county_line'

import { getPostitionlist } from '../../utils/api.js'
import { mapanalyse } from '../../utils/mapfanalyse.js'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        name: "地图显示",
        TabCur: 0,
        diquCUR: 0,
        shiCUR: 0,
        diqu: [{
            name: "乌鲁木齐",
            id: 0
        }],
        // shi: ['天山区', '沙依巴克区', '新市区', '水磨沟区', '头屯河区', '达坂城区', '米东区', '乌鲁木齐县'],
        shi: [],
        category: ['易燃易爆', '危险化学品', '人员密集场所', '旅游景区', '其他'],
        showModalStatus: false,
        longitude: null,
        latitude: null,
        polygons: [{
            points: [
                { longitude: 87.695739025, latitude: 43.636613935 },
                { longitude: 87.65244024, latitude: 43.711968500 },
                { longitude: 87.701925350, latitude: 43.765953725 },
                { longitude: 87.601888350, latitude: 43.802773060 },
                { longitude: 87.545260740, latitude: 43.637280875 },
                { longitude: 87.695739025, latitude: 43.636613935 }
            ],
            fillColor: "#5094d573",
            // width: 2,
            // dottedLine: true
        }],
        markers: [
            // {
            //     id: 0,
            //     iconPath: "../index/image/picture.jpg",
            //     latitude: null,
            //     longitude: null,
            //     width: 50,
            //     height: 50
            // }
        ],
        marginTop: '',
        navTo: '',
        activeKey: 0,
        alldata: null
    },
    /**
     * 生命周期函数--监听页面加载
     */
    powerDrawer: function(e) {
        var currentStatu = e.currentTarget.dataset.statu;
        this.util(currentStatu)
    },
    util: function(currentStatu) {
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        });
        this.animation = animation;
        animation.translateX(0).step();
        this.setData({
            animationData: animation.export()
        })

        setTimeout(function() {
            animation.translateX(220).step()
            this.setData({
                animationData: animation
            })
            if (currentStatu == "close") {
                this.setData({
                    showModalStatus: false
                });
            }
        }.bind(this), 200)
        if (currentStatu == "open") {
            this.setData({
                showModalStatus: true
            });
        }
    },
    // 获取第一次市县划分区域
    getFirstLoad_shi() {
        let area = mapanalyse(mapdata)
        this.setData({
            shi: area.namelist,
            alldata: area
        })
    },
    onLoad: function(options) {
        wx.hideShareMenu();
        var that = this;
        that.setData({
            marginTop: app.globalData.statusBarHeight + 'px',
            navTo: app.globalData.navHeight + 'px'
        })
        that.getFirstLoad_shi()
        let location = wx.getStorageSync("locations");
        let latitude = location.latitude;
        let longitude = location.longitude;
        // 获取到了本地存储的位置信息
        if (location) {
            console.log("获取到了位置")
            app.globalData.location = {
                latitude,
                longitude
            }
            that.setData({
                latitude,
                longitude,
                markers: [{
                    latitude,
                    longitude
                }]
            })
        }
        // 全局跟本地存储都没有位置信息
        if (!app.globalData.location && !location) {
            that.getMaker()
            console.log("没拿到app globaldata")
        }

        that.getStorageLatLng()
    },
    Gotback() {
        wx.navigateBack({
            delta: 1,
        })
    },
    diqu(e) {
        var that = this;

        let ID = e.currentTarget.dataset.id;

        that.setData({
            diquCUR: ID
        })
    },
    // 点击切换市县
    _shi(e) {
        var that = this;

        let index = e.currentTarget.dataset.index;
        console.log(index)
            // 挑选地区划分区域
            // let point = `polyline[${0}].points`
            // console.log(that.data.polyline[0].points)

        let points = this.data.alldata[index].geometry.coordinates[0]
        console.log(this.data.alldata[index].geometry.coordinates[0])
        that.setData({
            shiCUR: index,
            polygons: [{
                points,
                fillColor: "#5094d573"
            }],
            latitude: points[0].latitude,
            longitude: points[0].longitude
        })
        console.log(that.data.latitude, that.data.longitude)
    },
    _category(e) {
        var that = this;
        let index = e.currentTarget.dataset.index;
        that.setData({
            diquCUR: index,
        })
    },
    // 获取本地标点
    getStorageLatLng() {
        let that = this
        let latlngarr = wx.getStorageSync('latlngarr');
        getPostitionlist("getlatlon", {}).then(res => {
            // 执行返回数据之后操作方法
            that._drawMakers(res.data.xinjiang)
        })
    },
    _drawMakers(obj) {
        let that = this
        let arrs = []
        let markers = []
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                const element = obj[key];
                // console.log(element)
                for (const ele of element) {
                    arrs.push(ele)
                }
            }
        }
        arrs.forEach((ele, idx) => {

            // console.log(ele)

            if (ele.status == 0) {
                markers.push({
                    iconPath: '/images/check-on.png',
                    id: idx,
                    latitude: ele.lat_lon[0],
                    longitude: ele.lat_lon[1],
                    width: 25,
                    height: 25,
                    callout: {
                        content: ele.name,
                        padding: 5,
                        color: "#000",
                        borderRadius: 5,
                        bgColor: "#fff",
                        fontSize: '13',
                        display: "ALWAYS"
                    },
                })
            } else {
                markers.push({
                    iconPath: '/images/check-off.png',
                    id: idx,
                    latitude: ele.lat_lon[0],
                    longitude: ele.lat_lon[1],
                    width: 25,
                    height: 25,
                    callout: {
                        content: ele.name,
                        padding: 6,
                        color: "#000",
                        borderRadius: 5,
                        bgColor: "#fff",
                        fontSize: '13',
                        display: "ALWAYS"
                    },
                })
            }
            // console.log(markers)
        });
        that.setData({
            markers
        })
    },
    gotohere(e) {
        console.log(e)
        let _that = this
        let _markers = _that.data.markers
        let lat = ''
        let lon = ''
        _markers.forEach((ele, index) => {
            if (e.markerId == ele.id) {

                console.log(ele)
                lat = Number(ele.latitude);
                lon = Number(ele.longitude);
                wx.openLocation({ // 打开微信内置地图，实现导航功能（在内置地图里面打开地图软件）
                    latitude: lat,
                    longitude: lon,
                    name: "x",
                    success: function(res) {
                        console.log(res);
                    },
                    fail: function(res) {
                        console.log(res);
                    }
                })

            }
        })
    },
    // 重新定位
    getMaker() {
        let that = this
        wx.getLocation({
            type: "wgs84",
            success: function(res) {
                console.log("index 重新定位了一次");
                var latitude = res.latitude;
                var longitude = res.longitude;

                app.globalData.location = {
                    latitude,
                    longitude
                }
                that.setData({
                    latitude,
                    longitude,
                    markers: [{
                        latitude,
                        longitude
                    }]
                })
            }
        })
    },
    searchSomething(search, type) {
        let _this = this
        let key = app.globalData.mapKey
        let latitude = app.globalData.location.latitude
        let longitude = app.globalData.location.longitude
        console.log()
        wx.request({
            url: `https://apis.map.qq.com/ws/place/v1/search?keyword=${search}&boundary=nearby(${latitude},${longitude},5000)&key=${key}`,
            data: {},
            header: { 'content-type': 'application/json' },
            method: 'GET',
            dataType: 'json',
            success: (res) => {
                // console.log(res.data.data)
                _this.makeMarker(res.data.data, type)
            },
            fail: () => {
                wx.showToast({
                    title: '请求失败！！！！',
                    icon: 'fail',
                    image: '',
                    duration: 1500,
                    success: (result) => {

                    }
                });
            }
        });
    },
    makeMarker(arr, type) {
        let _this = this
        console.log(arr)
        let markers = []
        if (type == 0) {
            arr.forEach(ele => {
                markers.push({
                    iconPath: 'image/view.png',
                    id: ele.id,
                    latitude: ele.location.lat,
                    longitude: ele.location.lng,
                    width: 25,
                    height: 25,
                    callout: {
                        content: 'asdfasdf',
                        padding: 5,
                        color: "#000",
                        borderRadius: 5,
                        bgColor: "#fff",
                        fontSize: '15',
                        display: "BYCLICK"
                    },
                })

            });
        } else if (type == 1) {
            arr.forEach(ele => {
                markers.push({
                    iconPath: 'image/food.png',
                    id: ele.id,
                    latitude: ele.location.lat,
                    longitude: ele.location.lng,
                    width: 25,
                    height: 25,
                    callout: {
                        content: 'asdfasdf',
                        padding: 5,
                        color: "#000",
                        borderRadius: 5,
                        bgColor: "#fff",
                        fontSize: '15',
                        display: "BYCLICK"
                    },
                })
            });
        } else if (type == 2) {
            arr.forEach(ele => {
                markers.push({
                    iconPath: 'image/building.png',
                    id: ele.id,
                    latitude: ele.location.lat,
                    longitude: ele.location.lng,
                    width: 25,
                    height: 25,
                    callout: {
                        content: 'asdfasdf',
                        padding: 5,
                        color: "#000",
                        borderRadius: 5,
                        bgColor: "#fff",
                        fontSize: '15',
                        display: "BYCLICK"
                    },
                })
            });
        } else {
            console.log('asdfasdfasdf')
        }
        _this.setData({
            markers
        })
    },
    MakeOutLeftNav(e) {
        let that = this
        console.log("点击显示左侧区域")
        that.setData({
            modalName: e.currentTarget.dataset.target
        })
    },
    hideModal(e) {
        let that = this
        that.setData({
            modalName: null
        })
    },
    goToMine() {
        wx.switchTab({
            url: '../mine/mine'
        });
    },
    cancelModal() {
        this.hideModal()
    },
    certainModal() {
        // 这里发送请求 挑选标签之后
        let a = new Promise((resolve, reject) => {
            //...
            resolve('success')
        });

        a.then(result => {
            console.log(result); //success
        });

    },
    submit(e) {
        this.setData({
            showModalStatus: false
        });
    },
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})